package com.example.petstoreservice.controller;

import com.example.petstoreservice.entity.Cart;
import com.example.petstoreservice.entity.Result;
import com.example.petstoreservice.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @GetMapping("/{username}")
    public Result<List<Cart>> getByUsername(@PathVariable String username) {
        Result<List<Cart>> result = new Result<>();
        List<Cart> cartItems = cartService.getByUsername(username);
        if(cartItems != null) {
            result.setData(cartItems);
            result.setStatusCode("200");
        } else {
            result.setMessage("Get cart items failed");
            result.setStatusCode("400");
        }
        return result;
    }

    @PostMapping("/update")
    public Result<?> updateQuantityByIds(@RequestBody Map<String, Object> payload){
        int quantity = (int) payload.get("quantity");
        String cartId = (String) payload.get("cartId");
        if (cartService.updateQuantityByIds(quantity, cartId)) {
            return Result.success("Update cart successfully");
        } else {
            return Result.fail("Update cart failed");
        }
    }

    @PostMapping("/add")
    public Result<?> addCart(@RequestBody Cart cart) {
        if (cartService.addCart(cart)) {
            return Result.success("Add cart successfully");
        } else {
            return Result.fail("Add cart failed");
        }
    }
    
    @PostMapping("/delete")
    public Result<?> deleteItemByIds(@RequestBody List<String> Ids) {
        boolean deleteSuccess = false;
        for (String id : Ids) {
            if (cartService.deleteItemById(id)) {
                deleteSuccess = true;
            } else {
                deleteSuccess = false;
                break;
            }
        }

        if (deleteSuccess) {
            return Result.success("Delete cart item successfully");
        } else {
            return Result.fail("Delete cart item failed");
        }
    }
}
